package com.huike.report.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;

import com.alibaba.excel.util.CollectionUtils;
import com.huike.common.core.domain.AjaxResult;
import com.huike.common.utils.DateUtils;
import com.huike.report.domain.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.vo.IndexStatisticsVo;
import com.huike.clues.mapper.SysDeptMapper;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.clues.mapper.TbActivityMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.common.core.domain.entity.SysDept;
import com.huike.common.utils.SecurityUtils;
import com.huike.contract.domain.TbContract;
import com.huike.contract.mapper.TbContractMapper;
import com.huike.report.mapper.ReportMapper;
import com.huike.report.service.IReportService;

@Service
public class ReportServiceImpl implements IReportService {

    @Autowired
    private TbContractMapper contractMapper;


    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    @Autowired
    private TbClueMapper clueMapper;

    @Autowired
    private TbActivityMapper activityMapper;

    @Autowired
    private TbBusinessMapper businessMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private TbAssignRecordMapper assignRecordMapper;

    @Autowired
    private ReportMapper reportMapper;

    @Override
    public LineChartVO contractStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVO lineChartVo = new LineChartVO();
        try {
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            lineChartVo.setxAxis(timeList);
            List<LineSeriesVO> series = new ArrayList<>();
            List<Map<String, Object>> statistics = contractMapper.contractStatistics(beginCreateTime, endCreateTime);
            LineSeriesVO lineSeriesDTO1 = new LineSeriesVO();
            lineSeriesDTO1.setName("新增客户数");
            LineSeriesVO lineSeriesDTO2 = new LineSeriesVO();
            lineSeriesDTO2.setName("客户总数");
            int sum = 0;
            for (String s : timeList) {
                Optional optional = statistics.stream().filter(d -> d.get("dd").equals(s)).findFirst();
                if (optional.isPresent()) {
                    Map<String, Object> cuurentData = (Map<String, Object>) optional.get();
                    lineSeriesDTO1.getData().add(cuurentData.get("num"));
                    sum += Integer.parseInt(cuurentData.get("num").toString());
                } else {
                    lineSeriesDTO1.getData().add(0);
                }
                lineSeriesDTO2.getData().add(sum);
            }
            series.add(lineSeriesDTO1);
            series.add(lineSeriesDTO2);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return lineChartVo;
    }

    @Override
    public LineChartVO salesStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVO lineChartVo = new LineChartVO();
        try {
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            lineChartVo.setxAxis(timeList);
            List<LineSeriesVO> series = new ArrayList<>();
            List<Map<String, Object>> statistics = contractMapper.salesStatistics(beginCreateTime, endCreateTime);
            LineSeriesVO lineSeriesVo = new LineSeriesVO();
            lineSeriesVo.setName("销售统计");
            int sum = 0;
            for (String s : timeList) {
                Optional optional = statistics.stream().filter(d -> d.get("dd").equals(s)).findFirst();
                if (optional.isPresent()) {
                    Map<String, Object> cuurentData = (Map<String, Object>) optional.get();
                    lineSeriesVo.getData().add(cuurentData.get("sales"));
                } else {
                    lineSeriesVo.getData().add(0);
                }
            }
            series.add(lineSeriesVo);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
            // e.printStackTrace();
        }
        return lineChartVo;
    }


    /**
     * 渠道统计
     */
    @Override
    public List<Map<String, Object>> chanelStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.chanelStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue = (String) datum.get("channel");
            String lable = sysDictDataMapper.selectDictLabel("clues_item", subjectValue);
            datum.put("channel", lable);
        }
        return data;
    }

    @Override
    public List<TbContract> contractReportList(TbContract tbContract) {
        return contractMapper.selectTbContractList(tbContract);
    }


    @Override
    public List<Map<String, Object>> activityStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.activityStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            Long activityId = (Long) datum.get("activity_id");
            TbActivity tbActivity = activityMapper.selectTbActivityById(activityId);
            if (tbActivity == null) {
                datum.put("activity", "其他");
            } else {
                datum.put("activity", tbActivity.getName());
            }
        }
        return data;
    }

    /**
     * 按照部门统计销售
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> deptStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.deptStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            Long deptId = (Long) datum.get("dept_id");
            if (deptId != null) {
                SysDept dept = deptMapper.selectDeptById(deptId);
                datum.put("deptName", dept.getDeptName());
            }
        }
        return data;
    }


    /**
     * 按照渠道统计销售
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> channelStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.channelStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue = (String) datum.get("channel");
            if (subjectValue != null) {
                String lable = sysDictDataMapper.selectDictLabel("clues_item", subjectValue);
                datum.put("channel", lable);
            }
        }
        return data;
    }


    /**
     * 按照归属人统计销售
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> ownerShipStatisticsList(String beginCreateTime, String endCreateTime) {
        return contractMapper.ownerShipStatistics(beginCreateTime, endCreateTime);
    }


    @Override
    public List<TbClue> cluesStatisticsList(TbClue clue) {
        return clueMapper.selectTbClueForReport(clue);
    }

    @Override
    public List<ActivityStatisticsVo> activityStatisticsList(TbActivity query) {
        query.setStatus("2");
        List<TbActivity> activities = activityMapper.selectTbActivityList(query);
        Map<String, Object> timeMap = query.getParams();
        List<ActivityStatisticsVo> list = new ArrayList<>();
        for (TbActivity activity : activities) {
            ActivityStatisticsVo dto = new ActivityStatisticsVo();
            BeanUtils.copyProperties(activity, dto);
            TbClue tbClue = new TbClue();
            tbClue.setActivityId(activity.getId());
            tbClue.setChannel(activity.getChannel());
            tbClue.setParams(timeMap);
            Map<String, Object> clueCount = clueMapper.countByActivity(tbClue);
            if (clueCount != null) {
                dto.setCluesNum(Integer.parseInt(clueCount.get("total").toString()));
                if (clueCount.get("falseClues") != null) {
                    dto.setFalseCluesNum(Integer.parseInt(clueCount.get("falseClues").toString()));
                }
                if (clueCount.get("toBusiness") != null) {
                    dto.setBusinessNum(Integer.parseInt(clueCount.get("toBusiness").toString()));
                }
            }
            TbContract tbContract = new TbContract();
            tbContract.setChannel(activity.getChannel());
            tbContract.setActivityId(activity.getId());
            tbContract.setParams(timeMap);
            Map<String, Object> contractCount = contractMapper.countByActivity(tbContract);
            if (contractCount != null) {
                dto.setCustomersNum(Integer.parseInt(contractCount.get("customersNum").toString()));
                if (contractCount.get("amount") == null) {
                    dto.setAmount(0d);
                } else {
                    dto.setAmount((Double) contractCount.get("amount"));
                }
                if (contractCount.get("cost") == null) {
                    dto.setCost(0d);
                } else {
                    dto.setCost((Double) contractCount.get("cost"));
                }

            }
            list.add(dto);
        }
        return list;
    }


    /**
     * 新增线索折现图
     *
     * @param beginCreateTime 开始时间
     * @param endCreateTime   结束时间
     * @return 结果
     */
    @Override
    public LineChartVO getCluesStatistics(String beginCreateTime, String endCreateTime) {
        //创建结果集
        //封装每日新增线索的结果集
        LineSeriesVO lineSeriesVO = new LineSeriesVO();
        //设置名称
        lineSeriesVO.setName("新增线索数量");
        //封装线索总和的结果集
        LineSeriesVO lineSeriesVO2 = new LineSeriesVO();
        //设置名称
        lineSeriesVO2.setName("线索总数量");
        //最终要返回给前端的
        LineChartVO lineChartVO = new LineChartVO();
        //存放每日统计新增线索的个数
        List<Object> data = new ArrayList<>();
        //放每日线索的和
        List<Object> data2 = new ArrayList<>();
        //临时综合
        Integer sum = 0;
        try {
            //填补两个时间段中的空缺时间
            List<String> dates = findDates(beginCreateTime, endCreateTime);
            //封装时间
            lineChartVO.setxAxis(dates);
            //查询每个时间段的新增线索数量
            if (!CollectionUtils.isEmpty(dates)) {
                for (String date : dates) {
                    Integer num = reportMapper.findNewlyIncreased(date);
                    //封装结果
                    data.add(num);
                    //累加
                    sum += num;
                    data2.add(sum);
                }
            }
            // 封装最终结果
            //封装每日新增
            lineSeriesVO.setData(data);
            //封装每日累加
            lineSeriesVO2.setData(data2);
            //创建封装每日线索新增和线索总和的集合
            List<LineSeriesVO> series = new ArrayList<>();
            series.add(lineSeriesVO);
            series.add(lineSeriesVO2);
            //把这个集合放入最终要返回的lineChartVo对象里
            lineChartVO.setSeries(series);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return lineChartVO;
    }

    /**
     * *************看我看我**************
     * 传入两个时间范围，返回这两个时间范围内的所有时间，并保存在一个集合中
     *
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @return 结果
     * @throws ParseException 解析异常
     */
    public static List<String> findDates(String beginTime, String endTime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endTime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        System.out.println("时间==" + allDate);
        return allDate;
    }


    @Override
    public IndexVo getIndex(IndexStatisticsVo request) {
        Long deptId = request.getDeptId();
        TbAssignRecord tbAssignRecord = new TbAssignRecord();
        tbAssignRecord.setLatest("1");
        assignRecordMapper.selectAssignRecordList(tbAssignRecord);
        return null;
    }

    @Override
    public List<Map<String, Object>> salesStatisticsForIndex(IndexStatisticsVo request) {
        List<Map<String, Object>> list = contractMapper.contractStatisticsByUser(request);
        for (Map<String, Object> datum : list) {
            Long deptId = (Long) datum.get("dept_id");
            if (deptId != null) {
                SysDept dept = deptMapper.selectDeptById(deptId);
                datum.put("deptName", dept.getDeptName());
            }
        }
        return list;
    }


    /**
     * ************看我看我***********
     * 用我能少走很多路
     * 我是用来机选百分比的方法
     *
     * @param all
     * @param num
     * @return
     */
    private BigDecimal getRadio(Integer all, Long num) {
        if (all.intValue() == 0) {
            return new BigDecimal(0);
        }
        BigDecimal numBigDecimal = new BigDecimal(num);
        BigDecimal allBigDecimal = new BigDecimal(all);
        BigDecimal divide = numBigDecimal.divide(allBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
        return divide.multiply(new BigDecimal(100));
    }


    /**
     * 获取首页基本数据
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexBaseInfoVO getBaseInfo(String beginCreateTime, String endCreateTime) {
        //1）构建一个空的结果集对象
        IndexBaseInfoVO result = new IndexBaseInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();
        try {
            CompletableFuture<Integer> cluesNum = CompletableFuture.supplyAsync(() -> reportMapper.getCluesNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Integer> businessNum = CompletableFuture.supplyAsync(() -> reportMapper.getBusinessNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Integer> contractNum = CompletableFuture.supplyAsync(() -> reportMapper.getContractNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Double> salesAmount = CompletableFuture.supplyAsync(() -> reportMapper.getSalesAmount(beginCreateTime, endCreateTime, username));
            CompletableFuture.allOf(cluesNum, businessNum, contractNum, salesAmount).join();

            //封装结果集
            result.setCluesNum(cluesNum.get());
            result.setBusinessNum(businessNum.get());
            result.setContractNum(contractNum.get());
            result.setSalesAmount(salesAmount.get());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //4 返回结果集对象
        return result;
    }

    @Override
    public VulnerabilityMapVo getVulnerabilityMap(String beginCreateTime, String endCreateTime) {
        VulnerabilityMapVo vulnerabilityMapDTO = new VulnerabilityMapVo();
        //线索数
        vulnerabilityMapDTO.setCluesNums(clueMapper.countAllClues(beginCreateTime, endCreateTime));
        //有效线索数
        vulnerabilityMapDTO.setEffectiveCluesNums(clueMapper.effectiveCluesNums(beginCreateTime, endCreateTime));
        //商机数
        vulnerabilityMapDTO.setBusinessNums(businessMapper.businessNumsFromClue(beginCreateTime, endCreateTime));
        //合同数
        vulnerabilityMapDTO.setContractNums(contractMapper.contractNumsFromBusiness(beginCreateTime, endCreateTime));
        return vulnerabilityMapDTO;
    }


    /**
     * 商机转换龙虎榜
     *
     * @param request
     * @return
     */
    @Override
    public List<Map<String, Object>> businessChangeStatisticsForIndex(IndexStatisticsVo request) {
        int allBusiness = businessMapper.countAllBusiness(request.getBeginCreateTime(), request.getEndCreateTime());
        List<Map<String, Object>> list = businessMapper.countAllContractByUser(request);
        for (Map<String, Object> datum : list) {
            Long num = (Long) datum.get("num");
            datum.put("radio", getRadio(allBusiness, num));
        }
        return list;
    }


    /**
     * 线索转化龙虎榜
     */
    @Override
    public List<Map<String, Object>> clueChangeStatisticsForIndex(IndexStatisticsVo request) {
        int allclues = clueMapper.countAllClues(request.getBeginCreateTime(), request.getEndCreateTime());
        List<Map<String, Object>> list = clueMapper.countAllClueByUser(request);
        //计算转换率
        for (Map<String, Object> datum : list) {
            Long num = (Long) datum.get("num");
            datum.put("radio", getRadio(allclues, num));
        }
        return list;
    }

    /**
     * 今日简报
     *
     * @return 结果
     */
    @Override
    public IndexTodayInfoVO getTodayInfo() {
        //创建结果集对象
        IndexTodayInfoVO result = new IndexTodayInfoVO();
        //获取当前登陆的用户信息
        String username = SecurityUtils.getUsername();
        //获取当前的日期
        String currentDate = DateUtils.getDate();
        //查询并封装
        try {
            CompletableFuture<Integer> todayCluesNum = CompletableFuture.supplyAsync(() -> reportMapper.getTodayCluesNum(currentDate, username));
            CompletableFuture<Integer> todayBusinessNum = CompletableFuture.supplyAsync(() -> reportMapper.getTodayBusinessNum(currentDate, username));
            CompletableFuture<Integer> todayContractNum = CompletableFuture.supplyAsync(() -> reportMapper.getTodayContractNum(currentDate, username));
            CompletableFuture<Double> todaySalesAmount = CompletableFuture.supplyAsync(() -> reportMapper.getTodaySalesAmount(currentDate, username));
            CompletableFuture.allOf(todayCluesNum,todayBusinessNum,todayContractNum,todaySalesAmount).join();
            result.setTodayCluesNum(todayCluesNum.get());
            result.setTodayBusinessNum(todayBusinessNum.get());
            result.setTodayContractNum(todayContractNum.get());
            result.setTodaySalesAmount(todaySalesAmount.get());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //返回结果
        return result;
    }

    /**
     * 代办查询
     *
     * @param beginCreateTime 开始时间
     * @param endCreateTime   结束时间
     * @return
     */
    @Override
    public IndexTodoInfoVO getTodoInfo(String beginCreateTime, String endCreateTime) {
        //创建结果集
        IndexTodoInfoVO result = new IndexTodoInfoVO();
        //获取当前用户
        String username = SecurityUtils.getUsername();
        //封装结果
        //待跟进线索
        result.setTofollowedCluesNum(reportMapper.getToFollowedCluesNum(username, beginCreateTime, endCreateTime));
        //待跟进商机
        result.setTofollowedBusinessNum(reportMapper.getToFolloewdBusinessNum(username, beginCreateTime, endCreateTime));
        //判断权限
        //获取用户部门ID
        Long deptId = SecurityUtils.getDeptId();
        //判断部门id是否为研发部 和 销售部
        if (deptId == 214L || deptId == 103L) {
            //待分配线索
            result.setToallocatedCluesNum(reportMapper.getToallocatedCluesNum(beginCreateTime, endCreateTime));
            //待分配商机
            result.setToallocatedBusinessNum(reportMapper.getToallocatedBusinessNum(beginCreateTime, endCreateTime));
        }
        return result;
    }

    /**
     * 查询学科占比
     *
     * @param beginCreateTime 开始时间
     * @param endCreateTime   结束时间
     * @return 结果
     */
    @Override
    public List<PieChartVO> getSubjectStatistics(String beginCreateTime, String endCreateTime) {
        //封装结果
        return reportMapper.getSubjectStatistics(beginCreateTime, endCreateTime);

    }
}